package com.x.erp.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.x.erp.model.Car;
import com.x.erp.model.CarValuation;
import com.x.erp.model.Market;
import com.x.erp.rpc.CarRpcService;
import com.x.erp.rpc.CarValuationRpcService;
import com.x.erp.rpc.MarketRpcService;
import com.x.erp.thirdparty.Che300;
import com.x.erp.util.Constant;
import com.x.framework.controller.BaseController;
import com.x.framework.controller.ResultCode;
import com.x.framework.controller.ResultModel;
import com.x.framework.remote.HttpClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 车辆估值
 */
@RestController
@RequestMapping(value = "/che300")
public class Che300Controller extends BaseController{

	@Autowired
	private HttpClient httpClient;

	@Reference
	private CarValuationRpcService carValuationRpcService;

	@Reference
	private CarRpcService carRpcService;

	@Reference
	private MarketRpcService marketRpcService;

	/**
	 * 获取che300估值信息
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/getChe300CarPrice", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getChe300CarPrice(Che300 che300) {
		if (StringUtils.isEmpty(che300.getModelId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "车300车型ID不能为空");
		}
		if (StringUtils.isEmpty(che300.getZone())){
			return new ResultModel(ResultCode.RESULT_FAIL, "车300城市ID不能为空");
		}
		if (StringUtils.isEmpty(che300.getRegDate())){
			return new ResultModel(ResultCode.RESULT_FAIL, "车300首次上牌日期不能为空");
		}
		if (che300.getMile() == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "车300行驶里程不能为空");
		}
		String result = "";
		CarValuation carValuation =  null;
		List<CarValuation> list = new ArrayList<>();
		try {
			//请求车300接口，获取返回值
			result = httpClient.doGet(Constant.CHE300_GET_PRICE_URL + "?token=" + Constant.CHE300_TOKEN + "&modelId=" + che300.getModelId() + "&zone=" + che300.getZone() + "&regDate=" + che300.getRegDate() + "&mile=" + che300.getMile());
			if (StringUtils.isEmpty(result)){
				return new ResultModel(ResultCode.RESULT_FAIL, "车300返回数据为空");
			}
			JSONObject jsonObj = JSONObject.parseObject(result);
			//获取json对象中的json数组
			JSONArray arr = jsonObj.getJSONArray("eval_prices");
			if (arr != null && arr.size() > 0){
				for (int i = 0; i < arr.size(); i++) {
					carValuation = new CarValuation();
					carValuation.setStatus(jsonObj.getInteger("status"));
					carValuation.setValuationDefaultCarCondition(jsonObj.getString("default_car_condition"));
					carValuation.setValuationDetailReportUrl(jsonObj.getString("detail_report_url"));
					carValuation.setValuationFailReason(jsonObj.getString("error_msg"));
					carValuation.setValuationCondition(arr.getJSONObject(i).getString("condition"));
					carValuation.setValuationDealerLowBuyPrice(arr.getJSONObject(i).getBigDecimal("dealer_low_buy_price"));
					carValuation.setValuationDealerBuyPrice(arr.getJSONObject(i).getBigDecimal("dealer_buy_price"));
					carValuation.setValuationIndividualLowSoldPrice(arr.getJSONObject(i).getBigDecimal("individual_low_sold_price"));
					carValuation.setValuationIndividualPrice(arr.getJSONObject(i).getBigDecimal("individual_price"));
					carValuation.setValuationDealerLowSoldPrice(arr.getJSONObject(i).getBigDecimal("dealer_low_sold_price"));
					carValuation.setValuationDealerPrice(arr.getJSONObject(i).getBigDecimal("dealer_price"));
					carValuation.setValuationDealerHighSoldPrice(arr.getJSONObject(i).getBigDecimal("dealer_high_sold_price"));
					list.add(carValuation);
				}
			}else {
				carValuation = new CarValuation();
				carValuation.setStatus(jsonObj.getInteger("status"));
				carValuation.setValuationDefaultCarCondition(jsonObj.getString("default_car_condition"));
				carValuation.setValuationDetailReportUrl(jsonObj.getString("detail_report_url"));
				carValuation.setValuationFailReason(jsonObj.getString("error_msg"));
				list.add(carValuation);
			}
			return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", list);
		} catch (Exception e) {
			logger.error("车300返回估值信息出现异常！" + result , e);
			return new ResultModel(ResultCode.RESULT_FAIL, "车300返回估值信息出现异常");
		}
	}

	//初始化数据方法（禁用）
	@RequestMapping(value = "/init", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel init() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Car car = new Car();
		car.setMarketId("1");
		car.setCarStockState(20);
		List<Car> cars = carRpcService.selectCarList(car);
		Market market = new Market();
		Che300 che300 = new Che300();
		String cityId = "";
		for (Car car1 : cars){
			market.setMarketId(car1.getMarketId());
			List<Market> markets = marketRpcService.selectMarketList(market);
			if (markets != null && markets.size() > 0){
				cityId = markets.get(0).getCityId();
			}
			if (car1.getModelId() != null && StringUtils.isNotEmpty(cityId) && car1.getCarLicenceDate() != null && car1.getCarMileage() != null){
				che300.setModelId(car1.getModelId().toString());
				che300.setMile(car1.getCarMileage());
				che300.setRegDate(sdf.format(car1.getCarLicenceDate()));
				che300.setZone(cityId);
				ResultModel r = getChe300CarPrice(che300);
				if (r.getCode() == ResultCode.RESULT_SUCCESS){
					carValuationRpcService.insertCarValuationList(car1.getCarId(), (List<CarValuation>) r.getResult());
				}
			}
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "上传成功");
	}

}
